package org.jeecg.modules.business.outbound.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseAreaLocation;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaLocationService;
import org.jeecg.modules.business.outbound.entity.vo.CloseLightFilterVO;
import org.jeecg.modules.business.outbound.entity.vo.CloseOneLightVO;
import org.jeecg.modules.business.outbound.entity.vo.OpenLightFilterVO;
import org.jeecg.modules.business.outbound.entity.vo.RepertorySimpleVO;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskLightService;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskMaterialService;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.business.repertory.entity.WmsTaskMaterialLight;
import org.jeecg.modules.business.repertory.mapper.WmsTaskMaterialLightMapper;
import org.jeecg.modules.business.repertory.service.IWmsTaskMaterialLightService;
import org.jeecg.modules.dock.entity.WmsLightConfig;
import org.jeecg.modules.dock.entity.light.request.LightRequestVO;
import org.jeecg.modules.dock.service.IWmsLightConfigService;
import org.jeecg.modules.dock.service.LightIBSDockingService;
import org.jeecg.modules.flow.callback.enums.SimpleDocumentTypeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 出库任务-亮灯
 * @Author: jeecg-boot
 * @Date:   2023-08-09
 * @Version: V1.0
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class WmsOutReceiptTaskLightServiceImpl  implements IWmsOutReceiptTaskLightService {

    private final IWmsOutReceiptTaskService wmsOutReceiptTaskService;

    private final IWmsOutReceiptTaskMaterialService wmsOutReceiptTaskMaterialService;

    private final LightIBSDockingService lightIBSDockingService;

    private final IWmsLightConfigService wmsLightConfigService;

    private final IWmsTaskMaterialLightService wmsTaskMaterialLightService;

    private final IWmsBasicWarehouseAreaLocationService wmsBasicWarehouseAreaLocationService;

    private final WmsTaskMaterialLightMapper wmsTaskMaterialLightMapper;

    @Value("${wms.config.light.mode:simulate}")
    private String lightMode;

    /**
     * 按条件打开所有灯
     * @param openLightFilterVO
     */
    @Override
    public List<String> openAllLight(OpenLightFilterVO openLightFilterVO) {
        List<String> successIdList=new ArrayList<>();
        List<String> taskMaterialIdList = openLightFilterVO.getTaskMaterialIdList();
        if(CollectionUtil.isEmpty(taskMaterialIdList)){
            log.error("所有灯已经亮起来了");
            return successIdList;
        }
        //过滤掉已经亮灯
        List<WmsTaskMaterialLight> openTaskMaterialList = wmsTaskMaterialLightService.list(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                .eq(WmsTaskMaterialLight::getTaskId, openLightFilterVO.getTaskId())
                .eq(WmsTaskMaterialLight::getLightStatus,"1")
                .in(WmsTaskMaterialLight::getTaskMaterialId, taskMaterialIdList)
        );
        if(!CollectionUtil.isEmpty(openTaskMaterialList)){
            List<String> collect = openTaskMaterialList.stream().map(WmsTaskMaterialLight::getTaskMaterialId).collect(Collectors.toList());
            taskMaterialIdList.removeAll(collect);
            if(CollectionUtil.isEmpty(taskMaterialIdList)){
                log.error("所有灯已经亮起来了");
                return successIdList;
            }
        }
        //获取即时库存信息
        List<String> ipList=new ArrayList<>();
        List<WmsTaskMaterialLight> taskMaterialLightList=new ArrayList<>();
        for(String taskMaterialId:taskMaterialIdList){
            RepertorySimpleVO repertorySimpleVO = wmsOutReceiptTaskService.getMaterialRepertoryInfoByOutId(taskMaterialId);
            if(!StrUtil.isEmpty(repertorySimpleVO.getWmsBasicWarehouseId())
                    &&!StrUtil.isEmpty(repertorySimpleVO.getWmsBasicWarehouseAreaId())
                    &&!StrUtil.isEmpty(repertorySimpleVO.getWmsBasicWarehouseAreaLocationId())
            ){
                WmsLightConfig lightConfig = wmsLightConfigService.getOne(new LambdaQueryWrapper<WmsLightConfig>()
                        .eq(WmsLightConfig::getWmsBasicWarehouseId, repertorySimpleVO.getWmsBasicWarehouseId())
                        .eq(WmsLightConfig::getWmsBasicWarehouseAreaId, repertorySimpleVO.getWmsBasicWarehouseAreaId())
                        .eq(WmsLightConfig::getWmsBasicWarehouseAreaLocationId, repertorySimpleVO.getWmsBasicWarehouseAreaLocationId())
                        .last("LIMIT 1")
                );
                if(!Objects.isNull(lightConfig)&&!StrUtil.isEmpty(lightConfig.getLocationId())){
                    ipList.add(lightConfig.getLocationId()+"-"+lightConfig.getSiteCode());
                    WmsTaskMaterialLight wmsTaskMaterialLight=new WmsTaskMaterialLight();
                    wmsTaskMaterialLight.setSimpleDocumentStatus(SimpleDocumentTypeEnum.OUT_TASK.getCode());
                    wmsTaskMaterialLight.setTaskId(openLightFilterVO.getTaskId());
                    wmsTaskMaterialLight.setTaskMaterialId(taskMaterialId);
                    wmsTaskMaterialLight.setBatchCode(repertorySimpleVO.getBatchCode());
                    wmsTaskMaterialLight.setWmsBasicWarehouseId(repertorySimpleVO.getWmsBasicWarehouseId());
                    wmsTaskMaterialLight.setWmsBasicWarehouseAreaId(repertorySimpleVO.getWmsBasicWarehouseAreaId());
                    wmsTaskMaterialLight.setWmsBasicWarehouseAreaLocationId(repertorySimpleVO.getWmsBasicWarehouseAreaLocationId());
                    wmsTaskMaterialLight.setLocationId(lightConfig.getLocationId());
                    wmsTaskMaterialLight.setSiteCode(lightConfig.getSiteCode());
                    taskMaterialLightList.add(wmsTaskMaterialLight);
                }else{
                    log.error("taskMaterialId: {} 位置: {}这个物料的位置对应的安灯配置错误,安灯配置: {}",taskMaterialId,repertorySimpleVO,lightConfig);
                }
            }else{
                log.error("taskMaterialId: {}这个物料id查询不到库房库区库位信息错误,跳过,位置: {}",taskMaterialId,repertorySimpleVO);
            }
        }
        if(!CollectionUtil.isEmpty(ipList)){
            List<LightRequestVO> requestVOList = buildLightRequestVO(ipList, 1);

            if("simulate".equals(lightMode)){
                //以下跳过调用接口
                int result=1;
                if(result==1){
                    //代表响应成功处理响应数据
                    List<WmsTaskMaterialLight> successList=new ArrayList<>();
                    for(WmsTaskMaterialLight taskMaterialLight:taskMaterialLightList){
                        //删除
                        taskMaterialLight.setLightStatus("1");
                        if("1".equals(taskMaterialLight.getLightStatus())){
                            wmsTaskMaterialLightService.remove(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                                    .eq(WmsTaskMaterialLight::getTaskMaterialId,taskMaterialLight.getTaskMaterialId())
                                    .eq(WmsTaskMaterialLight::getLightStatus,"0")
                            );
                            successIdList.add(taskMaterialLight.getTaskMaterialId());
                            successList.add(taskMaterialLight);
                        }
                    }
                    wmsTaskMaterialLightService.saveBatch(successList);
                }
            }else{
                int result=0;
                try{
                    result = lightIBSDockingService.lightIBS(requestVOList);
                }catch (Exception e){
                    log.error("调用亮灯失败{}",e.getMessage());
                }
                if(result==1){
                    //代表响应成功处理响应数据
                    List<WmsTaskMaterialLight> successList=new ArrayList<>();
                    for(WmsTaskMaterialLight taskMaterialLight:taskMaterialLightList){
                        WmsLightConfig tempLightConfig = wmsLightConfigService.getOne(new LambdaQueryWrapper<WmsLightConfig>()
                                .eq(WmsLightConfig::getLocationId, taskMaterialLight.getLocationId())
                                .eq(WmsLightConfig::getSiteCode,taskMaterialLight.getSiteCode())
                        );
                        taskMaterialLight.setLightStatus(tempLightConfig.getState().toString());
                        taskMaterialLight.setSiteCode(tempLightConfig.getSiteCode());
                        if("1".equals(taskMaterialLight.getLightStatus())){
                            wmsTaskMaterialLightService.remove(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                                    .eq(WmsTaskMaterialLight::getTaskMaterialId,taskMaterialLight.getTaskMaterialId())
                                    .eq(WmsTaskMaterialLight::getLightStatus,"0")
                            );
                            successList.add(taskMaterialLight);
                        }
                    }
                    wmsTaskMaterialLightService.saveBatch(successList);
                }
                if(result==0){
                    //代表响应失败，暂时不做处理响应数据
                }
            }
        }
        return successIdList;
    }

    /**
     * 按条件关闭所有灯
     * @param closeLightFilterVO
     */
    @Override
    public List<String> closeAllLight(CloseLightFilterVO closeLightFilterVO) {
        List<String> successIdList=new ArrayList<>();
        List<WmsTaskMaterialLight> taskMaterialLightList=new ArrayList<>();
        if(Objects.isNull(closeLightFilterVO.getTaskMaterialIdList())){
            LambdaQueryWrapper<WmsTaskMaterialLight> queryWrapper=new LambdaQueryWrapper<WmsTaskMaterialLight>()
                    .eq(WmsTaskMaterialLight::getTaskId, closeLightFilterVO.getTaskId());
            taskMaterialLightList = wmsTaskMaterialLightService.list(queryWrapper);
        }else if(closeLightFilterVO.getTaskMaterialIdList().size()==0){
            //do nothing
        }else if(closeLightFilterVO.getTaskMaterialIdList().size()>0){
            //
            LambdaQueryWrapper<WmsTaskMaterialLight> queryWrapper=new LambdaQueryWrapper<WmsTaskMaterialLight>()
                    .eq(WmsTaskMaterialLight::getTaskId, closeLightFilterVO.getTaskId())
                    .in(WmsTaskMaterialLight::getTaskMaterialId,closeLightFilterVO.getTaskMaterialIdList());
            taskMaterialLightList = wmsTaskMaterialLightService.list(queryWrapper);
        }
        if(!CollectionUtil.isEmpty(taskMaterialLightList)){
            List<String> ipList = taskMaterialLightList.stream().map(s->s.getLocationId()+"-"+s.getSiteCode()).collect(Collectors.toList());
            List<LightRequestVO> requestVOList = buildLightRequestVO(ipList, 0);
            if("simulate".equals(lightMode)){
                int result=1;
                if(result==1){
                    //代表响应成功处理响应数据
                    for(WmsTaskMaterialLight taskMaterialLight:taskMaterialLightList){
                        taskMaterialLight.setLightStatus("0");
                        if("0".equals(taskMaterialLight.getLightStatus())){
                            successIdList.add(taskMaterialLight.getTaskMaterialId());
                            //删除记录
                            wmsTaskMaterialLightService.removeById(taskMaterialLight.getId());
                        }
                    }
                }
            }else{
                int result=0;
                try{
                    result = lightIBSDockingService.lightIBS(requestVOList);
                }catch (Exception e){
                    log.error("调用亮灯失败{}",e.getMessage());
                }
                if(result==1){
                    //代表响应成功处理响应数据
                    for(WmsTaskMaterialLight taskMaterialLight:taskMaterialLightList){
                        WmsLightConfig tempLightConfig = wmsLightConfigService.getOne(new LambdaQueryWrapper<WmsLightConfig>()
                                .eq(WmsLightConfig::getLocationId, taskMaterialLight.getLocationId())
                                .eq(WmsLightConfig::getSiteCode,taskMaterialLight.getSiteCode())
                        );
                        taskMaterialLight.setLightStatus(tempLightConfig.getState().toString());
                        if("0".equals(taskMaterialLight.getLightStatus())){
                            //删除记录
                            wmsTaskMaterialLightService.removeById(taskMaterialLight.getId());
                        }
                    }
                }
                if(result==0){
                    //代表响应失败，暂时不做处理响应数据
                }
            }
        }
        return successIdList;
    }

    /**
     * 扫码关闭一个灯
     * @param closeOneLightVO
     */
    @Override
    public String closeOneLight(CloseOneLightVO closeOneLightVO) {

        WmsTaskMaterialLight taskMaterialLightOne = wmsTaskMaterialLightService.getOne(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                .eq(WmsTaskMaterialLight::getTaskId, closeOneLightVO.getTaskId())
                .eq(WmsTaskMaterialLight::getBatchCode, closeOneLightVO.getBatchCode())
                .last("LIMIT 1")
        );
        if(Objects.isNull(taskMaterialLightOne)){
            return null;
        }
        List<WmsTaskMaterialLight> otherTaskMaterialList = wmsTaskMaterialLightService.list(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                .eq(WmsTaskMaterialLight::getTaskId, taskMaterialLightOne.getTaskId())
                .eq(WmsTaskMaterialLight::getWmsBasicWarehouseId, taskMaterialLightOne.getWmsBasicWarehouseId())
                .eq(WmsTaskMaterialLight::getWmsBasicWarehouseAreaId, taskMaterialLightOne.getWmsBasicWarehouseAreaId())
                .eq(WmsTaskMaterialLight::getWmsBasicWarehouseAreaLocationId, taskMaterialLightOne.getWmsBasicWarehouseAreaLocationId())
                .ne(WmsTaskMaterialLight::getBatchCode, taskMaterialLightOne.getBatchCode()));

        if(!CollectionUtil.isEmpty(otherTaskMaterialList)){
            String errorMessage="库位存在其他待出库批次号";
            WmsTaskMaterialLight otherTaskMaterial = otherTaskMaterialList.get(0);
            WmsBasicWarehouseAreaLocation areaLocation = wmsBasicWarehouseAreaLocationService.getById(otherTaskMaterial.getWmsBasicWarehouseAreaLocationId());
            if(!Objects.isNull(areaLocation)){
                errorMessage=areaLocation.getName()+errorMessage;
            }
            errorMessage+=(otherTaskMaterial.getBatchCode()+"，不灭灯");
            //直接删除亮灯状态信息
            //wmsTaskMaterialLightService.removeById(taskMaterialLightOne.getId());
            return errorMessage;
        }
        if("simulate".equals(lightMode)){
            int result = 1;
            if(result==1){
                //代表响应成功处理响应数据
                taskMaterialLightOne.setLightStatus("0");
                if("0".equals(taskMaterialLightOne.getLightStatus())){
                    //删除其他同位置的亮灯
                    wmsTaskMaterialLightService.remove(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                            .eq(WmsTaskMaterialLight::getSimpleDocumentStatus,SimpleDocumentTypeEnum.OUT_TASK.getCode())
                            .eq(WmsTaskMaterialLight::getLightStatus,"1")
                            .eq(WmsTaskMaterialLight::getLocationId,taskMaterialLightOne.getLocationId())
                            .eq(WmsTaskMaterialLight::getSiteCode,taskMaterialLightOne.getSiteCode())
                    );
                    //删除记录
                    wmsTaskMaterialLightService.removeById(taskMaterialLightOne.getId());
                }
            }
        }else{
            int result=0;
            LightRequestVO lightRequestVO=new LightRequestVO();
            lightRequestVO.setLocationId(taskMaterialLightOne.getLocationId()+"-"+taskMaterialLightOne.getSiteCode());
            lightRequestVO.setState(0);
            lightRequestVO.setLightColor(32);
            List<LightRequestVO> requestVOList=new ArrayList<>();
            requestVOList.add(lightRequestVO);
            try{
                result = lightIBSDockingService.lightIBS(requestVOList);
            }catch (Exception e){
                log.error("调用亮灯失败{}",e.getMessage());
            }
            if(result==1){
                //代表响应成功处理响应数据
                WmsLightConfig tempLightConfig = wmsLightConfigService.getOne(new LambdaQueryWrapper<WmsLightConfig>()
                        .eq(WmsLightConfig::getLocationId, taskMaterialLightOne.getLocationId())
                        .eq(WmsLightConfig::getSiteCode,taskMaterialLightOne.getSiteCode())
                );
                taskMaterialLightOne.setLightStatus(tempLightConfig.getState().toString());
                if("0".equals(taskMaterialLightOne.getLightStatus())){
                    //删除其他同位置的亮灯
                    wmsTaskMaterialLightService.remove(new LambdaQueryWrapper<WmsTaskMaterialLight>()
                            .eq(WmsTaskMaterialLight::getSimpleDocumentStatus,SimpleDocumentTypeEnum.OUT_TASK.getCode())
                            .eq(WmsTaskMaterialLight::getLightStatus,"1")
                            .eq(WmsTaskMaterialLight::getLocationId,taskMaterialLightOne.getLocationId())
                            .eq(WmsTaskMaterialLight::getSiteCode,taskMaterialLightOne.getSiteCode())
                    );
                    //删除记录
                    wmsTaskMaterialLightService.removeById(taskMaterialLightOne.getId());
                }
            }
            if(result==0){
                //代表响应失败，暂时不做处理响应数据
            }
        }
        return null;
    }

    /**
     *
     * @param taskMaterialId
     * @return
     */
    @Override
    public String getLightStatus(String taskMaterialId) {
        WmsTaskMaterialLight one=wmsTaskMaterialLightMapper.getRecordIgnoreDelete(taskMaterialId);

        if(Objects.isNull(one)){
            return "0";
        }else{
            WmsLightConfig wmsLightConfig = wmsLightConfigService.getOne(new LambdaQueryWrapper<WmsLightConfig>()
                    .eq(WmsLightConfig::getLocationId, one.getLocationId())
            );
            if(Objects.isNull(wmsLightConfig)){
                return "0";
            }else{
                return wmsLightConfig.getState()+"";
            }

        }
    }

    private List<LightRequestVO> buildLightRequestVO(List<String> ipList,Integer state){
        List<LightRequestVO> requestVOList=new ArrayList<>();
        if(CollectionUtil.isEmpty(ipList)){
            return requestVOList;
        }

        for(String ip: ipList){
            LightRequestVO lightRequestVO=new LightRequestVO();
            lightRequestVO.setLocationId(ip);
            lightRequestVO.setState(state);
            lightRequestVO.setLightColor(32);
            requestVOList.add(lightRequestVO);
        }
        return requestVOList;
    }


}
